<?php
/**
 * 认证模型
 * 
 * @author 高强
 */

class LoginModel
{
	private $_authAdapter;
	private $_output;
	
	
	/**
	 * 初始化认证组件
	 * 
	 * @ignore
	 */
	public function __construct()
	{
		$dbAdapter = Zend_Registry::get('db');
		$this->_output = new Custom_Controller_Plugin_Output();
		
		$this->_authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$this->_authAdapter->setTableName('st_user');
		$this->_authAdapter->setIdentityColumn('account');
		$this->_authAdapter->setCredentialColumn('password');
	}
	
	/**
	 * 登录认证
	 * 
	 * @param string $account   用户名
	 * @param string $password  密码
	 */
	public function logined($account, $password)
	{
		$check = $this->checkParam($account, $password);
		
		if(empty($check))
			return false;
		
		
		$password = md5($password);
		
		$this->_authAdapter->setIdentity($account);
		$this->_authAdapter->setCredential($password);
		
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($this->_authAdapter);
		
		if($result->isValid())
		{
			$storage = $auth->getStorage();
			$storage->write(
				$this->_authAdapter->getResultRowObject(null, 'password')
			);
			
			return $this->_output->success(true);
		}
		
		return $this->_output->success(false, '用户名或者密码错误');
	}
	
	/**
	 * 登录前的验证
	 * 
	 * @param string $account 用户帐号
	 * @param string $password 密码
	 * 
	 * @return boolean
	 */
	public function checkParam($account, $password)
	{
		if(!isset($account) || empty($account))
			return $this->_output->success(false, '用户名没有填写');
		
		if(!isset($password) || empty($password))
			return $this->_output->success(false, '密码没有填写');
		
		
		return true;
	}
	
	/**
	 * 登出系统
	 * 
	 * @return boolean
	 */
	public function logout()
	{
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
	}
}